var common = require('../../../utils/common.js');
var app = getApp();
var baseUrl = app.url;

Page({
    data: {
        files: [],
        datalist:{},
        __UPLOADS__:app.__UPLOADS__,
        urls:[],
        descNum:0   
    },
    onLoad: function(options){
        this.setData({id:options.id});
        var id = this.data.id;
        common.bestCurl('GET','/maintain/detail',res=>{
            if(res.statusCode == 200){
                if(res.data.maintain_file.length!=0){
                    var file_arr = Array();
                    for (var i = 0; i < res.data.maintain_file.length; i++) {
                        file_arr[i] = new Object();
                        file_arr[i]['id'] = res.data.maintain_file[i].id;
                        file_arr[i]['type'] =1;
                        url = app.__UPLOADS__+'/'+res.data.maintain_file[i].file_url;
                        file_arr[i]['url'] = url;
                        file_arr[i]['show_url'] = url;
                    }
                    this.setData({datalist:res.data,files:file_arr})
                }else{
                    this.setData({datalist:res.data})
                }   
            }
        },{'id':id})
    },
    bindMaintainChange: function (e) {
        this.setData({
            maintain_time: e.detail.value
        })
    },
    clickWrongIcon:function(event){
        id = event.target.id;
        var obj = this.data.files;
        var urls = this.data.urls;        
        var that = this;        
        if(event.currentTarget.dataset.file.type==1){
            wx.showModal({
                title: '确认要删除吗?',
                cancelText: "取消",
                confirmText: "确定",
                success: function (res) {
                    if (res.confirm) {
                        common.bestCurl('GET','/maintain/del_file',res=>{
                            if(res.statusCode == 200){
                                if(res.data.code == 1){
                                    wx.showToast({
                                        title: '删除成功',
                                        icon: '',
                                        duration: 2000
                                    });
                                    setTimeout(function(){
                                        obj.splice(id,1); 
                                        that.setData({files:obj});
                                    },2000)
                                }else{
                                    wx.showToast({
                                        title: '未删除成功,请重试',
                                        icon: '',
                                        duration: 3000
                                    });
                                }
                            }
                        },{'id':event.currentTarget.dataset.file.id})
                    }else{
                        console.log('用户点击辅助操作')
                    }
                }
            });
        }else{
            url = event.currentTarget.dataset.file.url;
            var num = urls.indexOf(url);
            urls.splice(num,1);
            obj.splice(id,1); 
            this.setData({files:obj,urls:urls})
        }
    },
    chooseImage: function (e) {
        var that = this;
        wx.chooseImage({
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success: function (res) {
                var file_arr = [];
                for (var i = 0; i < res.tempFilePaths.length; i++) {
                    file_arr[i] = new Object;
                    file_arr[i]['id'] = 0;
                    file_arr[i]['type'] =2;
                    file_arr[i]['url'] = res.tempFilePaths[i];
                    file_arr[i]['show_url'] = res.tempFilePaths[i];
                }
                that.setData({files: that.data.files.concat(file_arr),urls:that.data.urls.concat(res.tempFilePaths)});                
            }
        })               
    },
    showFile:function (event) {
        var url = event.currentTarget.dataset.url;
        var fileUrl = url;
        var extStart = url.lastIndexOf(".");
        var ext = url.substring(extStart, url.length).toUpperCase();
        var pic = [
            '.JPG',
            '.PNG',
            '.JPEG',
            '.BMP',
            '.GIF',
            '.WEBP'
        ];
        var fileType = [
            '.DOC',
            '.XLS',
            '.PPT',
            '.PDF',
            '.DOCX',
            '.XLSX',
            '.PPTX'
        ];
        console.log(ext);
        if(pic.indexOf(ext)!=-1){
            wx.previewImage({
                current: '', 
                urls: [
                    fileUrl
                ] 
            })
        }else if(fileType.indexOf(ext)!=-1){
            wx.showLoading({
              title: '加载中',
              mask:true
            });
            wx.downloadFile({
                url: fileUrl, 
                success: function(res) {
                    wx.hideLoading();
                    if (res.statusCode === 200) {
                        wx.openDocument({
                            filePath: res.tempFilePath,
                            success: function (res) {
                                console.log('打开文档成功')
                            }
                        })
                    }
                }
            });
        }else{
            wx.showModal({
                content: '非法文件,禁止预览',
                showCancel: false,
            });        
        }       
    },  
    descChange:function (event) {
        this.setData({descNum:event.detail.cursor});       
    },   
    formSubmit:function (event) {
        var formData = event.detail.value;
        var inputVal = this.data.inputVal;
        var car_sn = event.currentTarget.dataset.car_sn;
        var id = this.data.id;

        common.bestCurl('POST','/maintain/edit',res=>{
            if(res.statusCode == 200){
                if(res.data.code == 1){
                    var urls = this.data.urls;
                    var flag = 0;
                    if(urls.length>0){
                        wx.showLoading({
                            title: '图片上传中',
                            icon: 'loading',
                            mask:true
                        });
                        let SESSID = wx.getStorageSync('PHPSESSID');
                        if(SESSID){
                            var PHPSESSID = '?PHPSESSID='+SESSID;
                        }else{
                            PHPSESSID = '?';
                        }
                        url=baseUrl+'/maintain/add_file'+PHPSESSID;
                        for (var i = urls.length - 1; i >= 0; i--) {
                            wx.uploadFile({
                                url: url, 
                                filePath: urls[i],
                                name: 'uploadfile',
                                formData:{
                                    'id': id
                                },
                                success: function(res){
                                    flag++;
                                    if(urls.length == flag){
                                        wx.hideLoading()
                                        wx.showToast({
                                            title: '更新成功',
                                            icon: '',
                                            duration: 5000
                                        });
                                        setTimeout(res=>{
                                            wx.redirectTo({
                                                url: '../list/list'
                                            })

                                        },2000)
                                    }     
                                }
                            })
                        }
                    }else{
                        wx.showToast({
                            title: '更新成功',
                            icon: '',
                            duration: 5000
                        });
                        setTimeout(res=>{
                            wx.redirectTo({
                                url: '../list/list'
                            })

                        },2000)
                    }
                }
            }
        },Object.assign({'car_sn':car_sn},{'id':id},formData))              
    },
    notPic:function (event) {
        id = event.target.id;
        var files = this.data.files;
        var file_arr = this.data.files[id];
        file_arr['show_url'] = app.__PUBLIC__+'/images/PDF.png';
        files.splice(id,1,file_arr)
        this.setData({files:files})
    }
});

